package com.uzai.console.service.takebal.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.RedEnvelope;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.redpacket.RedPacketCreateAndSendDto;
import com.uzai.console.dto.feign.redpacket.WxredPacketCreateAndSendDto;
import com.uzai.console.dto.feign.wxcontacts.WxGroupMemberRegisterDto;
import com.uzai.console.dto.takebal.redpackettemplate.*;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.RedPacketFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.AlarmMsgPushProducerService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.takebal.RedPacketTemplateService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.cms.activity.CmsActivityInfoVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.sysmaterial.SysMaterialVo;
import com.uzai.console.vo.takebal.redpacket.RedPacketInfoVo;
import com.uzai.console.vo.takebal.redpackettemplate.RedPacketTemplateInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/***
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class RedPacketTemplateServiceImpl implements RedPacketTemplateService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedPacketTemplateMapper redPacketTemplateMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RedPacketFeignService redPacketFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private RedPacketRandomMapper redPacketRandomMapper;
    @Autowired
    private RedPacketRandomDetailMapper redPacketRandomDetailMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private SysDomainMapper sysDomainMapper;

    /**
     * 查询所有红包模板列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketTemplateQuery
     * @return null
     */
    public List<RedPacketTemplateInfoVo> findRedPacketTemplateList(RedPacketTemplateQuery redPacketTemplateQuery){
        List<RedPacketTemplateInfoVo> redPacketInfoVoList = new ArrayList<>();
        //查询红包模板列表
        List<RedPacketTemplate> redPacketTemplateList = redPacketTemplateMapper.findByList(redPacketTemplateQuery);
        if(redPacketTemplateList != null){
            for (RedPacketTemplate redPacketTemplate : redPacketTemplateList){
                RedPacketTemplateInfoVo redPacketTemplateInfoVo = new RedPacketTemplateInfoVo();
                BeanUtils.copyProperties(redPacketTemplate, redPacketTemplateInfoVo);
                redPacketInfoVoList.add(redPacketTemplateInfoVo);
            }
        }
        return redPacketInfoVoList;
    }

    /**
     * 分页查询红包模板列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketTemplateQuery
     * @return null
     */
    public Page<RedPacketTemplateInfoVo> findRedPacketTemplatePage(RedPacketTemplateQuery redPacketTemplateQuery){
        List<RedPacketTemplateInfoVo> redPacketInfoVoList = new ArrayList<>();
        //执行分页查询对象
        Page<RedPacketTemplate> page = new Page<>();
        redPacketTemplateQuery.convert(page);
        //查询红包模板列表
        List<RedPacketTemplate> redPacketTemplateList = redPacketTemplateMapper.findByList(page, redPacketTemplateQuery);
        if(redPacketTemplateList != null){
            for (RedPacketTemplate redPacketTemplate : redPacketTemplateList){
                RedPacketTemplateInfoVo redPacketTemplateInfoVo = new RedPacketTemplateInfoVo();
                BeanUtils.copyProperties(redPacketTemplate, redPacketTemplateInfoVo);
                redPacketInfoVoList.add(redPacketTemplateInfoVo);
            }
        }

        //返回到页面分页对象
        Page<RedPacketTemplateInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(redPacketInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 修改红包模板
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketTemplateUpdateDto
     * @return null
     */
    @Transactional
    public void updateRedPacketTemplateInfo(RedPacketTemplateUpdateDto redPacketTemplateUpdateDto){
        List<RedPacketTemplateInfoDto> redPacketTemplateInfoDtoList = redPacketTemplateUpdateDto.getRedPacketTemplateInfoDtoList();

        if(redPacketTemplateInfoDtoList == null || redPacketTemplateInfoDtoList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包模板信息不能为空");
        }

        Integer now = DateUtil.getNowTime();

        for (RedPacketTemplateInfoDto redPacketTemplateInfoDto : redPacketTemplateInfoDtoList) {

            redPacketTemplateInfoDto.setMerId(redPacketTemplateUpdateDto.getMerId());

            if(redPacketTemplateInfoDto.getNumber() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板序号不能为空");
            }

            if(StringUtils.isBlank(redPacketTemplateInfoDto.getName())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板名称不能为空");
            }

            if(StringUtils.isBlank(redPacketTemplateInfoDto.getTitle())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "卡片标题不能为空");
            }

            if(StringUtils.isBlank(redPacketTemplateInfoDto.getDesc())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "卡片描述不能为空");
            }

            if(StringUtils.isBlank(redPacketTemplateInfoDto.getImg())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "卡片图片不能为空");
            }

            if(redPacketTemplateInfoDto.getId() != null){ //存在，修改

                //根据名称查询
                RedPacketTemplate redPacketTemplate_name = redPacketTemplateMapper.selectByName(redPacketTemplateUpdateDto.getMerId(), redPacketTemplateInfoDto.getName());
                if(redPacketTemplate_name != null && redPacketTemplate_name.getId().longValue() != redPacketTemplateInfoDto.getId()){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板名称不能重复");
                }

                RedPacketTemplate redPacketTemplate = redPacketTemplateMapper.selectById(redPacketTemplateInfoDto.getId(), redPacketTemplateUpdateDto.getMerId());
                if(redPacketTemplate != null){
                    redPacketTemplate.setTitle(redPacketTemplateInfoDto.getTitle());
                    redPacketTemplate.setDesc(redPacketTemplateInfoDto.getDesc());
                    redPacketTemplate.setImg(redPacketTemplateInfoDto.getImg());
                    redPacketTemplate.setReplay(redPacketTemplateInfoDto.getReplay());
                    redPacketTemplate.setName(redPacketTemplateInfoDto.getName());
                    redPacketTemplate.setNumber(redPacketTemplateInfoDto.getNumber());
                    redPacketTemplate.setUpdateTime(now);
                    redPacketTemplateMapper.updateById(redPacketTemplate);
                }
            }else{

                //根据名称查询
                RedPacketTemplate redPacketTemplate_name = redPacketTemplateMapper.selectByName(redPacketTemplateUpdateDto.getMerId(), redPacketTemplateInfoDto.getName());
                if (redPacketTemplate_name != null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板名称不能重复");
                }

                RedPacketTemplate redPacketTemplate = new RedPacketTemplate();
                redPacketTemplate.setId(IdWorker.getId());
                redPacketTemplate.setMerId(redPacketTemplateUpdateDto.getMerId());
                redPacketTemplate.setTitle(redPacketTemplateInfoDto.getTitle());
                redPacketTemplate.setDesc(redPacketTemplateInfoDto.getDesc());
                redPacketTemplate.setImg(redPacketTemplateInfoDto.getImg());
                redPacketTemplate.setReplay(redPacketTemplateInfoDto.getReplay());
                redPacketTemplate.setName(redPacketTemplateInfoDto.getName());
                redPacketTemplate.setNumber(redPacketTemplateInfoDto.getNumber());
                redPacketTemplate.setUpdateTime(now);
                redPacketTemplate.setCreateTime(now);
                redPacketTemplateMapper.insert(redPacketTemplate);
            }
        }
    }

    /**
     * 批量手动发送红包
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketSendDto
     * @return null
     */
    public void batchSendRedPacket(RedPacketSendDto redPacketSendDto){

        if(StringUtils.isBlank(redPacketSendDto.getDeviceType())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员所属端不能为空");
        }

        if(Tools.getDouble(redPacketSendDto.getMoney()).doubleValue() <= 0.0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须大于0");
        }

        if(redPacketSendDto.getTemplateId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择红包模板");
        }
        RedPacketTemplate redPacketTemplate = redPacketTemplateMapper.selectById(redPacketSendDto.getTemplateId(), redPacketSendDto.getMerId());
        if(redPacketTemplate == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包模板id不存在");
        }

        //微信红包
        if(Tools.getInteger(redPacketTemplate.getModel()).intValue() == 1
            && Tools.getStr(redPacketSendDto.getDeviceType()).equals(DeviceTypeEnum.DT_ANDROID_WECHAT.getKey())
            && Tools.getInteger(redPacketSendDto.getType()).intValue() == 0){
            sendWxRedPacket(redPacketSendDto); //发送微信红包
        }else{//红包卡片
            if(redPacketSendDto.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())){//公众号，只支持私聊发送指定会员红包
                //发送指定会员红包
                sendRedPacket(redPacketSendDto);
            }else{ //个人微信和企业微信支持群聊和私聊
                if(Tools.getInteger(redPacketSendDto.getType()) == 0){ //私聊只支持指定会员红包
                    //发送指定会员红包
                    sendRedPacket(redPacketSendDto);
                }else{ //群聊同时支持单个群指定多个会员发送红包；多个群发送拼手气会员红包
                    if(Tools.getInteger(redPacketSendDto.getRedPackageType()) == 0){ //指定多个会员发送红包
                        //获取多个指定会员微信id列表
                        List<String> userWxidList = redPacketSendDto.getUserWxidList();
                        if(userWxidList == null || userWxidList.size() == 0){
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员wxid列表");
                        }
                        for (String userWxid : userWxidList) {
                            try {
                                RedPacketSendDto redPacketSendDto_userWxid = new RedPacketSendDto();
                                BeanUtils.copyProperties(redPacketSendDto, redPacketSendDto_userWxid);
                                redPacketSendDto_userWxid.setUserWxid(userWxid);
                                //发送指定会员红包
                                sendRedPacket(redPacketSendDto_userWxid);
                            }catch (Exception e){
                                logger.error("-手动发送指定红包异常-error={}", e.getMessage());
                                continue;
                            }
                        }
                    }else{//多个群发送拼手气会员红包
                        List<String> groupIdList = redPacketSendDto.getGroupIdList();
                        if(groupIdList == null || groupIdList.size() == 0){
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择群id列表");
                        }

                        //人数
                        Integer totalCount = redPacketSendDto.getTotalCount();
                        if(totalCount == 0){
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包人数必须大于0");
                        }

                        //总金额
                        Double money = Tools.getDouble(redPacketSendDto.getMoney());
                        if(money.doubleValue() <= 0.0){
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须大于0");
                        }

                        //每人至少领取0.3元，则所有人至少领取总金额为
                        double minPensonMoney = 0.3d;
                        double minTotalMoney = Math.mul(totalCount, minPensonMoney);
                        //剩下的总金额
                        double subTotalMoney = Math.sub(money, minTotalMoney);
                        if(subTotalMoney < 0.00d){
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须满足每人至少领取0.3元");
                        }

                        for (String groupId : groupIdList) {
                            try {
                                RedPacketSendDto redPacketSendDto_groupId = new RedPacketSendDto();
                                BeanUtils.copyProperties(redPacketSendDto, redPacketSendDto_groupId);
                                redPacketSendDto_groupId.setGroupId(groupId);
                                //发送拼手气红包
                                sendRedPacketRandom(redPacketSendDto_groupId);
                            }catch (Exception e){
                                logger.error("-手动发送拼手气红包异常-error={}", e.getMessage());
                                continue;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 手动发送红包卡片
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketSendDto
     * @return null
     */
    public void sendRedPacket(RedPacketSendDto redPacketSendDto){

        Long merId = redPacketSendDto.getMerId();

        if(StringUtils.isBlank(redPacketSendDto.getDeviceType())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员所属端不能为空");
        }

        if(Tools.getDouble(redPacketSendDto.getMoney()).doubleValue() <= 0.0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须大于0");
        }

        if(redPacketSendDto.getTemplateId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择红包模板");
        }
        RedPacketTemplate redPacketTemplate = redPacketTemplateMapper.selectById(redPacketSendDto.getTemplateId(), redPacketSendDto.getMerId());
        if(redPacketTemplate == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包模板id不存在");
        }

        //发送红包的会员id
        Long userId = null;
        //获取群微信id
        String groupWxid = null;

        //公众号会员，只支持私聊。
        if(redPacketSendDto.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())){
            if(redPacketSendDto.getUserId() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
            }
            //公众号会员id
            userId = redPacketSendDto.getUserId();
        }else{ //个人微信和企业微信，同时支持私聊和群聊
            if(redPacketSendDto.getType() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择类型");
            }
            if(redPacketSendDto.getType().intValue() == 0){//私发，需要查询会员
                if(redPacketSendDto.getUserId() == null){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
                }
                //公众号会员id
                userId = redPacketSendDto.getUserId();
            }else{//群聊，需要输入群id和成员wxid
                if(StringUtils.isBlank(redPacketSendDto.getGroupId())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择群");
                }
                if(StringUtils.isBlank(redPacketSendDto.getUserWxid())){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入用户wxid");
                }

                //群聊，需要判断群是否配置支付功能
                if(redPacketSendDto.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信群
                    //查询微信群
                    String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
                    uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, merId);

                    Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, redPacketSendDto.getGroupId(), null);
                    EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
                    if(esWxContacts == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此个人微信群不存在");
                    }
                    //判断是否为群通讯录
                    if(Tools.getInteger(esWxContacts.getUserType()).intValue() != 1){//
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的微信群id不是群通信录");
                    }
                    //获取群微信id
                    groupWxid = esWxContacts.getWxid();

                    if(esWxContacts.getManagePlanId() == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群还未配置管理方案");
                    }
                    //配置方案
                    ConfigPlan configPlan = configPlanMapper.selectById(esWxContacts.getManagePlanId(), merId);
                    if(configPlan == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案不存在或已经删除");
                    }

                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), merId);
                    if(sysPlugin == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案插件不存在或已经删除");
                    }
                    //判断管理方案中功能设置是否开启了支付功能
                    JSONObject jsonObject = null;
                    try {
                        jsonObject  = JSONObject.parseObject(sysPlugin.getData());
                    }catch (Exception e){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案设置的基本功能数据格式有误");
                    }

                    if(jsonObject != null){
                        //提现开关(0-关；1-开)
                        Integer txSwitch = Tools.getInteger(jsonObject.getInteger("txSwitch"));
                        if(txSwitch.intValue() != 1){//
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案中的功能设置中的支付功能未开启");
                        }
                    }else{
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先配置此群管理方案中的功能设置");
                    }

                    //查询微信id是否已经注册会员
                    User userInfoByWxid = userService.findUserInfoByWxid(merId, redPacketSendDto.getUserWxid(), redPacketSendDto.getDeviceType());
                    if(userInfoByWxid != null){//查询到会员，表示已经注册会员
                        userId = userInfoByWxid.getId();
                    }else{//未查询到，表示还未注册会员，则调用群成员注册微服务接口
                        //先查询出此群微信id在群中的成员信息
                        //群成员主键merId_groupWxid_wxid
                        String groupMemberId = merId + "_" + esWxContacts.getWxid() + "_" + redPacketSendDto.getUserWxid();
                        //通过查询运营商其他索引分片获取分片索引
                        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, merId);
                        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, groupMemberId, null);
                        EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
                        if(esWxGroupMember == null){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信群成员不存在");
                        }

                        WxGroupMemberRegisterDto wxGroupMemberRegisterDto = new WxGroupMemberRegisterDto();
                        wxGroupMemberRegisterDto.setMerId(merId);
                        wxGroupMemberRegisterDto.setDeviceId(esWxContacts.getDeviceId());
                        wxGroupMemberRegisterDto.setDeviceType(esWxContacts.getDeviceType());
                        wxGroupMemberRegisterDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                        wxGroupMemberRegisterDto.setGroupWxid(esWxContacts.getWxid()); //群wxid
                        wxGroupMemberRegisterDto.setWxid(redPacketSendDto.getUserWxid()); //群成员wxid
                        wxGroupMemberRegisterDto.setHeadImg(esWxGroupMember.getHimg()); //群成员头像
                        wxGroupMemberRegisterDto.setNickName(esWxGroupMember.getNick());//群昵称
                        wxGroupMemberRegisterDto.setParentWxid(esWxGroupMember.getInviterWxid()); //邀请人微信id
                        UzaiRespVo<Long> uzaiRespVo = wxContactsFeignService.userreg3(wxGroupMemberRegisterDto);
                        logger.info("--调用群内成员注册微服务返回会员id接口--para={},result={}",JSONObject.toJSONString(wxGroupMemberRegisterDto),JSONObject.toJSONString(uzaiRespVo));
                        if(uzaiRespVo.getCode() == 200){
                            userId = uzaiRespVo.getData();
                        }
                    }
                }else{ //企业微信群
                    //查询微信群
                    String uzai_workwx_group_info = EsIndexName.UZAI_WORKWX_GROUP_INFO;
                    uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_info, merId);
                    Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, redPacketSendDto.getGroupId(), null);
                    EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
                    if(esWorkWxGroupInfo == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此企业微信群不存在");
                    }
                    //获取群微信id
                    groupWxid = esWorkWxGroupInfo.getGroupId();
                    //判断此群微信id是否配置了管理方案
                    if(esWorkWxGroupInfo.getManagePlanId() == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群还未配置管理方案");
                    }
                    //配置方案
                    ConfigPlan configPlan = configPlanMapper.selectById(esWorkWxGroupInfo.getManagePlanId(), merId);
                    if(configPlan == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案不存在或已经删除");
                    }

                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), merId);
                    if(sysPlugin == null){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案插件不存在或已经删除");
                    }
                    //判断管理方案中功能设置是否开启了支付功能
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = JSONObject.parseObject(sysPlugin.getData());
                    }catch (Exception e){
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案设置的基本功能数据格式有误");
                    }

                    if(jsonObject != null){
                        //提现开关(0-关；1-开)
                        Integer txSwitch = Tools.getInteger(jsonObject.getInteger("txSwitch"));
                        if(txSwitch.intValue() != 1){//
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案中的功能设置中的支付功能未开启");
                        }
                    }else{
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先配置此群管理方案中的功能设置");
                    }

                    //查询微信id是否已经注册会员
                    User userInfoByWxid = userService.findUserInfoByWxid(merId, redPacketSendDto.getUserWxid(), redPacketSendDto.getDeviceType());
                    if(userInfoByWxid != null){//查询到会员，表示已经注册会员
                        userId = userInfoByWxid.getId();
                    }else {//未查询到，表示还未注册会员，则调用群成员注册微服务接口
                        //先查询出此群微信id在群中的成员信息
                        //群成员主键merId_groupWxid_wxid
                        String groupMemberId = merId + "_" + esWorkWxGroupInfo.getGroupId() + "_" + redPacketSendDto.getUserWxid();
                        //通过查询运营商其他索引分片获取分片索引
                        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, merId);
                        Map<String, Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, groupMemberId, null);
                        EsWorkWxGroupMember esWorkWxGroupMember = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
                        if (esWorkWxGroupMember == null) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群成员不存在");
                        }
                        WxGroupMemberRegisterDto wxGroupMemberRegisterDto = new WxGroupMemberRegisterDto();
                        wxGroupMemberRegisterDto.setMerId(merId);
                        wxGroupMemberRegisterDto.setDeviceId(esWorkWxGroupInfo.getDeviceId());
                        wxGroupMemberRegisterDto.setDeviceType(esWorkWxGroupInfo.getDeviceType());
                        wxGroupMemberRegisterDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
                        wxGroupMemberRegisterDto.setGroupWxid(esWorkWxGroupInfo.getGroupId()); //群wxid
                        wxGroupMemberRegisterDto.setWxid(redPacketSendDto.getUserWxid());      //群成员wxid
                        wxGroupMemberRegisterDto.setHeadImg(esWorkWxGroupMember.getHimg());    //群成员头像
                        wxGroupMemberRegisterDto.setNickName(esWorkWxGroupMember.getNick());   //群昵称
                        wxGroupMemberRegisterDto.setParentWxid(esWorkWxGroupMember.getInviterWxid()); //邀请人微信id
                        UzaiRespVo<Long> uzaiRespVo = wxContactsFeignService.userreg3(wxGroupMemberRegisterDto);
                        logger.info("--调用群内成员注册微服务返回会员id接口--para={},result={}", JSONObject.toJSONString(wxGroupMemberRegisterDto), JSONObject.toJSONString(uzaiRespVo));
                        if (uzaiRespVo.getCode() == 200) {
                            userId = uzaiRespVo.getData();
                        }
                    }
                }
            }
        }

        if(userId == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未找到会员wxid对应的会员id");
        }

        User user = userService.findUserInfo(userId, redPacketSendDto.getDeviceType(), redPacketSendDto.getMerId());

        if(user == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员不存在");
        }

        if(user.getDeviceUniqueId() == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人为空");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), redPacketSendDto.getDeviceType(), user.getMerId());

        if(device == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        Integer now = DateUtil.getNowTime();
        String tradeno = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        //创建并发送红包
        RedPacketCreateAndSendDto redPacketCreateAndSendDto = new RedPacketCreateAndSendDto();
        redPacketCreateAndSendDto.setUserId(userId);
        redPacketCreateAndSendDto.setDeviceType(device.getRecvmsgType());
        redPacketCreateAndSendDto.setMerId(redPacketSendDto.getMerId());
        redPacketCreateAndSendDto.setDeviceUniqueId(user.getDeviceUniqueId());
        redPacketCreateAndSendDto.setMoney(redPacketSendDto.getMoney());
        redPacketCreateAndSendDto.setTemplateId(redPacketSendDto.getTemplateId());
        redPacketCreateAndSendDto.setTradeno(tradeno);
        redPacketCreateAndSendDto.setWxGroupId(groupWxid);
        redPacketCreateAndSendDto.setType(RedPackTypeEnum.MANUAL_SEND.getValue());

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        UzaiRespVo<Boolean> uzaiRespVo = redPacketFeignService.createAndSendRedpacket(redPacketCreateAndSendDto);
        stopWatch.stop();
        logger.info("-调用手动发送红包接口耗时分析：" + stopWatch.prettyPrint());

        logger.info("--调用手动发送红包接口--para={}, result={}", JSONObject.toJSONString(redPacketCreateAndSendDto), JSONObject.toJSONString(uzaiRespVo));

        try {
            Thread.sleep(500);
        }catch (Exception e){

        }

        if(uzaiRespVo.getCode() == 200 && uzaiRespVo.getData()){
            //手动发送红包成功-增加手动发送红包异常报警通知
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(redPacketSendDto.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_SEND_REDPACK.getValue()); //手动发送红包通知
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, redPacketSendDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            ext.put("childuser", loginVo.getLoginName());
            ext.put("money", redPacketSendDto.getMoney());
            ext.put("phone", loginVo.getMobile());
            ext.put("userid", user.getId());
            ext.put("nick", Tools.getStr(user.getNickName()));

            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo  uzaiRespVo_msg = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送手动发送红包报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_msg));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            //是否需要发送红包回复消息
            if(StringUtils.isNotBlank(redPacketTemplate.getReplay())){
                //发送MQ消息
                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                msgDto.setId(IdWorker.getId());
                msgDto.setMerId(user.getMerId());
                msgDto.setDeviceUniqueId(user.getDeviceUniqueId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);

                //公众号，没有群发还是私发这个字段
                if(redPacketSendDto.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())){
                    noticeMsgDto.setBizUserId(user.getBizUserId());
                }else{
                    if(redPacketSendDto.getType().intValue() == 0){ //私发
                        noticeMsgDto.setBizUserId(user.getBizUserId());
                    }else{//群发
                        noticeMsgDto.setBizUserId(groupWxid);
                    }
                }

                String content = redPacketTemplate.getReplay().replace("[昵称]",user.getNickName()).replace("[红包金额]", String.valueOf(redPacketSendDto.getMoney()));
                noticeMsgDto.setContent(content);
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }

    }

    /**
     * 手动发送手气红包卡片
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketSendDto
     * @return null
     */
    @Transactional
    public void sendRedPacketRandom(RedPacketSendDto redPacketSendDto){
        Long merId = redPacketSendDto.getMerId();

        if(StringUtils.isBlank(redPacketSendDto.getDeviceType())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员所属端不能为空");
        }

        //总金额
        Double money = Tools.getDouble(redPacketSendDto.getMoney());
        if(money.doubleValue() <= 0.0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须大于0");
        }

        //人数
        Integer totalCount = redPacketSendDto.getTotalCount();
        if(totalCount == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包人数必须大于0");
        }

        //每人至少领取0.3元，则所有人至少领取总金额为
        double minPensonMoney = 0.3d;
        double minTotalMoney = Math.mul(totalCount, minPensonMoney);
        //剩下的总金额
        double subTotalMoney = Math.sub(money, minTotalMoney);
        if(subTotalMoney < 0.00d){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须满足每人至少领取0.3元");
        }

        if(redPacketSendDto.getTemplateId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择红包模板");
        }
        RedPacketTemplate redPacketTemplate = redPacketTemplateMapper.selectById(redPacketSendDto.getTemplateId(), redPacketSendDto.getMerId());
        if(redPacketTemplate == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包模板id不存在");
        }

        if(StringUtils.isBlank(redPacketSendDto.getGroupId())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择群");
        }

        //获取群微信id
        String groupWxid = null;
        //群管理机器人唯一id
        Long deviceUniqueId = null;
        if(redPacketSendDto.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信群
            //查询微信群
            String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
            uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, merId);

            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, redPacketSendDto.getGroupId(), null);
            EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
            if(esWxContacts == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此个人微信群不存在");
            }
            //判断是否为群通讯录
            if(Tools.getInteger(esWxContacts.getUserType()).intValue() != 1){//
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的微信群id不是群通信录");
            }
            //获取群微信id
            groupWxid = esWxContacts.getWxid();
            //获取群管理机器人唯一id
            deviceUniqueId = esWxContacts.getDeviceUniqueId();

            //缓存中的微信群管理方案key
            if(esWxContacts.getManagePlanId() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群还未配置管理方案");
            }
            //配置方案
            ConfigPlan configPlan = configPlanMapper.selectById(esWxContacts.getManagePlanId(), merId);
            if(configPlan == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案不存在或已经删除");
            }

            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), merId);
            if(sysPlugin == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案插件不存在或已经删除");
            }
            //判断管理方案中功能设置是否开启了支付功能
            JSONObject jsonObject = null;
            try {
                jsonObject  = JSONObject.parseObject(sysPlugin.getData());
            }catch (Exception e){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案设置的基本功能数据格式有误");
            }

            if(jsonObject != null){
                //提现开关(0-关；1-开)
                Integer txSwitch = Tools.getInteger(jsonObject.getInteger("txSwitch"));
                if(txSwitch.intValue() != 1){//
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案中的功能设置中的支付功能未开启");
                }
            }else{
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先配置此群管理方案中的功能设置");
            }
        }else{ //企业微信群
            //查询微信群
            String uzai_workwx_group_info = EsIndexName.UZAI_WORKWX_GROUP_INFO;
            uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_info, merId);
            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, redPacketSendDto.getGroupId(), null);
            EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
            if(esWorkWxGroupInfo == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此企业微信群不存在");
            }
            //获取群微信id
            groupWxid = esWorkWxGroupInfo.getGroupId();
            //获取群管理机器人唯一id
            deviceUniqueId = esWorkWxGroupInfo.getDeviceUniqueId();
            //判断此群微信id是否配置了管理方案
            if(esWorkWxGroupInfo.getManagePlanId() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群还未配置管理方案");
            }
            //配置方案
            ConfigPlan configPlan = configPlanMapper.selectById(esWorkWxGroupInfo.getManagePlanId(), merId);
            if(configPlan == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案不存在或已经删除");
            }

            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), merId);
            if(sysPlugin == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群配置的管理方案插件不存在或已经删除");
            }
            //判断管理方案中功能设置是否开启了支付功能
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(sysPlugin.getData());
            }catch (Exception e){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案设置的基本功能数据格式有误");
            }

            if(jsonObject != null){
                //提现开关(0-关；1-开)
                Integer txSwitch = Tools.getInteger(jsonObject.getInteger("txSwitch"));
                if(txSwitch.intValue() != 1){//
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此群管理方案中的功能设置中的支付功能未开启");
                }
            }else{
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先配置此群管理方案中的功能设置");
            }
        }

        if(StringUtils.isBlank(groupWxid)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到群wxid");
        }

        if(deviceUniqueId == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群管理机器人为空");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, redPacketSendDto.getDeviceType(), merId);

        if(device == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群绑定的机器人不存在或已删除");
        }

        //保存随机红包
        //随机红包id
        int now = DateUtil.getNowTime();
        Long randomId = IdWorker.getId();
        RedPacketRandom redPacketRandom = new RedPacketRandom();
        redPacketRandom.setId(randomId);
        redPacketRandom.setDeviceType(redPacketSendDto.getDeviceType());
        redPacketRandom.setDeviceUniqueId(deviceUniqueId);
        redPacketRandom.setMerId(merId);
        redPacketRandom.setTemplateId(redPacketSendDto.getTemplateId());
        redPacketRandom.setTotalAmount(redPacketSendDto.getMoney());
        redPacketRandom.setTotalCount(redPacketSendDto.getTotalCount());
        redPacketRandom.setUseCount(0);
        redPacketRandom.setUseAmount(0.00D);
        redPacketRandom.setWxGroupId(groupWxid);
        redPacketRandom.setVersion(0);
        redPacketRandom.setCreateTime(now);
        redPacketRandom.setUpdateTime(now);
        redPacketRandomMapper.insert(redPacketRandom);

        //保存随机红包明细
        RedPacketRandomDetail redPacketRandomDetail = new RedPacketRandomDetail();
        //随机红包切割
        //每个红包至少0.3,将每个人至少领取的0.3元去除之后，剩下的总金额进行二分均值随机分配
        List<Double> detailMoneyList = RedEnvelope.doubleMeanMethod(subTotalMoney, redPacketSendDto.getTotalCount());
        if(detailMoneyList == null || detailMoneyList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "随机红包数有误");
        }
        for (Double detailMoney : detailMoneyList) {
            double amount = Math.add(detailMoney, minPensonMoney);
            redPacketRandomDetail.setId(IdWorker.getId());
            redPacketRandomDetail.setAmount(amount);
            redPacketRandomDetail.setMerId(merId);
            redPacketRandomDetail.setRandomId(randomId);
            redPacketRandomDetail.setStatus(0); //默认未领取
            redPacketRandomDetail.setVersion(0);
            redPacketRandomDetail.setCreateTime(now);
            redPacketRandomDetail.setUpdateTime(now);
            redPacketRandomDetailMapper.insert(redPacketRandomDetail);
        }

        //获取CMS域名
        String key = String.format(RedisCacheKeyEnum.CMS_BASE_CONFIG.getKey(),merId);
        String cmsConfigStr = (String) redisTemplate.opsForValue().get(key);
        String mallDomain = "0";
        if (cmsConfigStr!=null){
            JSONObject cmsConfig = JSONObject.parseObject(cmsConfigStr);
            mallDomain = cmsConfig.getString("mallDomain");
        }
        Long domainId = null;
        String domain = null;
        if (mallDomain.startsWith("http")){
            domain = mallDomain;
        }else {
            domainId = 0L;
            try {
                domainId = Long.parseLong(mallDomain);
            } catch (Exception e) {
                logger.error("err:",e);
            }

            SysDomain sysDomain = null;
            logger.info("merId::{},domainId:{}",new Object[]{merId,domainId});
            if (domainId.longValue() == 0) {
                // cms中间页
                sysDomain = sysDomainMapper.selectById(0L,0L);
            } else {
                // 自有域名
                sysDomain = sysDomainMapper.selectById(domainId, merId);
            }
            domain = sysDomain.getSiteDomain();
        }

        //发送红包卡片
        MsgDto<NoticeMsgDto> msgDto_redcard = new MsgDto<>();
        msgDto_redcard.setDeviceType(device.getRecvmsgType());
        msgDto_redcard.setDeviceUniqueId(deviceUniqueId);
        msgDto_redcard.setId(IdWorker.getId());
        msgDto_redcard.setMerId(merId);
        msgDto_redcard.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
        //String redPacketRandomCardUrl = "https://cmssvr.52youzai.net/user/redPacket/random/take?randomId=%s&deviceUniqueId=%s&deviceType=%s&merId=%s&wxGroupId=%s";
        String redPacketRandomCardUrl = domain + uzaiConsoleSysConfig.getRedPacketRandomCardUrl();
        redPacketRandomCardUrl = String.format(redPacketRandomCardUrl, randomId, deviceUniqueId, redPacketSendDto.getDeviceType(), merId, groupWxid);
        JSONObject cardVo = new JSONObject();
        cardVo.put("title", redPacketTemplate.getTitle());
        cardVo.put("desc", redPacketTemplate.getDesc());
        cardVo.put("imageUrl", redPacketTemplate.getImg());
        cardVo.put("url", redPacketRandomCardUrl);
        String cardStr = JSONObject.toJSONString(cardVo);
        NoticeMsgDto noticeMsgDto_redcard = new NoticeMsgDto();
        noticeMsgDto_redcard.setBizUserId(groupWxid);
        noticeMsgDto_redcard.setGroupId(groupWxid);
        noticeMsgDto_redcard.setContent(cardStr);
        noticeMsgDto_redcard.setContentType(MessageTypeEnum.MT_URL_CARD.getValue());
        noticeMsgDto_redcard.setReqId(null);
        noticeMsgDto_redcard.setMsgBizType(null);
        noticeMsgDto_redcard.setDelay(0);
        msgDto_redcard.setContent(noticeMsgDto_redcard);
        msgDto_redcard.setDelay(0);
        noticeMsgPushProducerService.sendMessage(msgDto_redcard);

        //手动发送红包成功-增加手动发送红包异常报警通知
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(redPacketSendDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_SEND_REDPACK.getValue()); //手动发送红包通知
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, redPacketSendDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        ext.put("childuser", loginVo.getLoginName());
        ext.put("money", redPacketSendDto.getMoney());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo  uzaiRespVo_msg = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送手动发送红包报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_msg));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

    }

    /**
     * 手动发送微信红包
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketSendDto
     * @return null
     */
    public void sendWxRedPacket(RedPacketSendDto redPacketSendDto){

        Long merId = redPacketSendDto.getMerId();

        if(StringUtils.isBlank(redPacketSendDto.getDeviceType())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员所属端不能为空");
        }

        if(Tools.getDouble(redPacketSendDto.getMoney()).doubleValue() <= 0.0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额必须大于0");
        }

        if(redPacketSendDto.getTemplateId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择红包模板");
        }

        RedPacketTemplate redPacketTemplate = redPacketTemplateMapper.selectById(redPacketSendDto.getTemplateId(), redPacketSendDto.getMerId());
        if(redPacketTemplate == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包模板id不存在");
        }

        //发送微信红包
        if(Tools.getInteger(redPacketTemplate.getModel()).intValue() != 1){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此红包模板不是发送微信红包");
        }

        //发送红包的会员id
        Long userId = null;

        if(redPacketSendDto.getType() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择类型");
        }

        if(!redPacketSendDto.getDeviceType().equals(DeviceTypeEnum.DT_ANDROID_WECHAT.getKey())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有个人微信手机端才能发送微信红包");
        }

        if(redPacketSendDto.getType().intValue() == 0){//私发，需要查询会员
            if(redPacketSendDto.getUserId() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
            }
        }

        //会员id
        userId = redPacketSendDto.getUserId();

        if(userId == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员id不能为空");
        }

        User user = userService.findUserInfo(userId, redPacketSendDto.getDeviceType(), redPacketSendDto.getMerId());

        if(user == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员不存在");
        }

        if(user.getDeviceUniqueId() == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人为空");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), redPacketSendDto.getDeviceType(), user.getMerId());

        if(device == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        //发送红包返回对象
        UzaiRespVo<Boolean> uzaiRespVo = null;
        Integer now = DateUtil.getNowTime();
        String tradeno = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();

        //此设备移动端在线，则发送微信红包
        if(device.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT_VALUE){
            //查询机器人配置中的提现插件是否配置了微信红包支付密码
            if(device.getConfigId() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此会员所在机器人没有配置方案");
            }

            ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
            if(configPlan == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此会员所在机器人配置方案不存在");
            }

            //提现插件id
            if(configPlan.getUserTakeBalId() == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此会员所在机器人配置方案未配置提现插件");
            }

            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
            if(sysPlugin == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此会员所在机器人配置方案提现设置不存在");
            }

            JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
            if(jsonObject == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此会员所在机器人配置方案提现设置数据不正确");
            }
            //微信红包支付密码
            String wx_redpacket_pay_password = Tools.getStr(jsonObject.getString("wx_redpacket_pay_password"));
            if(StringUtils.isBlank(wx_redpacket_pay_password)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此会员所在机器人配置方案提现设置未配置微信红包支付密码");
            }

            //创建并发送微信红包
            WxredPacketCreateAndSendDto wxredPacketCreateAndSendDto = new WxredPacketCreateAndSendDto();
            wxredPacketCreateAndSendDto.setUserId(userId);
            wxredPacketCreateAndSendDto.setBizUserId(user.getBizUserId());
            wxredPacketCreateAndSendDto.setDeviceType(device.getRecvmsgType());
            wxredPacketCreateAndSendDto.setMerId(redPacketSendDto.getMerId());
            wxredPacketCreateAndSendDto.setDeviceUniqueId(user.getDeviceUniqueId());
            wxredPacketCreateAndSendDto.setMoney(redPacketSendDto.getMoney());
            wxredPacketCreateAndSendDto.setTemplateId(redPacketSendDto.getTemplateId());
            wxredPacketCreateAndSendDto.setTradeno(tradeno);
            wxredPacketCreateAndSendDto.setWxRedpacketPayPassword(wx_redpacket_pay_password); //微信红包支付密码
            wxredPacketCreateAndSendDto.setType(RedPackTypeEnum.MANUAL_SEND.getValue());

            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            uzaiRespVo = redPacketFeignService.createAndSendWxredpacket(wxredPacketCreateAndSendDto);
            stopWatch.stop();
            logger.info("-调用手动发送微信红包接口耗时分析：" + stopWatch.prettyPrint());

            logger.info("--调用手动发送微信红包接口--para={}, result={}", JSONObject.toJSONString(wxredPacketCreateAndSendDto), JSONObject.toJSONString(uzaiRespVo));

        }else{  //PC端在线，默认发送红包卡片
            //创建并发送红包
            RedPacketCreateAndSendDto redPacketCreateAndSendDto = new RedPacketCreateAndSendDto();
            redPacketCreateAndSendDto.setUserId(userId);
            redPacketCreateAndSendDto.setDeviceType(device.getRecvmsgType());
            redPacketCreateAndSendDto.setMerId(redPacketSendDto.getMerId());
            redPacketCreateAndSendDto.setDeviceUniqueId(user.getDeviceUniqueId());
            redPacketCreateAndSendDto.setMoney(redPacketSendDto.getMoney());
            redPacketCreateAndSendDto.setTemplateId(redPacketSendDto.getTemplateId());
            redPacketCreateAndSendDto.setTradeno(tradeno);
            redPacketCreateAndSendDto.setWxGroupId(null); //个人微信私发红包才会发送微信红包
            redPacketCreateAndSendDto.setType(RedPackTypeEnum.MANUAL_SEND.getValue());

            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            uzaiRespVo = redPacketFeignService.createAndSendRedpacket(redPacketCreateAndSendDto);
            stopWatch.stop();
            logger.info("-调用手动发送红包接口耗时分析：" + stopWatch.prettyPrint());

            logger.info("--调用手动发送红包接口--para={}, result={}", JSONObject.toJSONString(redPacketCreateAndSendDto), JSONObject.toJSONString(uzaiRespVo));
        }

        try {
            Thread.sleep(500);
        }catch (Exception e){

        }

        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200 && uzaiRespVo.getData()){
            //手动发送微信红包成功-增加手动发送微信红包异常报警通知
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(redPacketSendDto.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_SEND_REDPACK.getValue()); //手动发送微信红包通知
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, redPacketSendDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            ext.put("childuser", loginVo.getLoginName());
            ext.put("money", redPacketSendDto.getMoney());
            ext.put("phone", loginVo.getMobile());
            ext.put("userid", user.getId());
            ext.put("nick", Tools.getStr(user.getNickName()));
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo  uzaiRespVo_msg = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送手动发送微信红包报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_msg));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            //是否需要发送微信红包回复消息
            if(StringUtils.isNotBlank(redPacketTemplate.getReplay())){
                //发送MQ消息
                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                msgDto.setId(IdWorker.getId());
                msgDto.setMerId(user.getMerId());
                msgDto.setDeviceUniqueId(user.getDeviceUniqueId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);
                noticeMsgDto.setBizUserId(user.getBizUserId());
                String content = redPacketTemplate.getReplay().replace("[昵称]",user.getNickName()).replace("[红包金额]", String.valueOf(redPacketSendDto.getMoney()));
                noticeMsgDto.setContent(content);
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }
    }


    /**
     * 添加红包模板
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketTemplateInfoDto
     * @return null
     */
    @Transactional
    public void saveRedPacketTemplate(RedPacketTemplateInfoDto redPacketTemplateInfoDto){

        Integer now = DateUtil.getNowTime();

        if(StringUtils.isBlank(redPacketTemplateInfoDto.getName())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板名称不能为空");
        }

        if(redPacketTemplateInfoDto.getMoney() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "红包金额不能为空");
        }

        if(redPacketTemplateInfoDto.getRepeated() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "重复领取不能为空");
        }

        if(redPacketTemplateInfoDto.getModel() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "是否发送微信红包不能为空");
        }

        //发送红包卡片，必填字段
        if(redPacketTemplateInfoDto.getModel().intValue() == 0){
            if(StringUtils.isBlank(redPacketTemplateInfoDto.getTitle())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "卡片标题不能为空");
            }

            if(StringUtils.isBlank(redPacketTemplateInfoDto.getImg())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "卡片图片不能为空");
            }
        }

        if(redPacketTemplateInfoDto.getId() != null){ //存在，修改
            //根据名称查询
            RedPacketTemplate redPacketTemplate_name = redPacketTemplateMapper.selectByName(redPacketTemplateInfoDto.getMerId(), redPacketTemplateInfoDto.getName());
            if(redPacketTemplate_name != null && redPacketTemplate_name.getId().longValue() != redPacketTemplateInfoDto.getId()){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板名称不能重复");
            }

            RedPacketTemplate redPacketTemplate = redPacketTemplateMapper.selectById(redPacketTemplateInfoDto.getId(), redPacketTemplateInfoDto.getMerId());
            if(redPacketTemplate != null){
                redPacketTemplate.setTitle(redPacketTemplateInfoDto.getTitle());
                redPacketTemplate.setDesc(redPacketTemplateInfoDto.getDesc());
                redPacketTemplate.setImg(redPacketTemplateInfoDto.getImg());
                redPacketTemplate.setReplay(redPacketTemplateInfoDto.getReplay());
                redPacketTemplate.setName(redPacketTemplateInfoDto.getName());
                redPacketTemplate.setMoney(redPacketTemplateInfoDto.getMoney());
                redPacketTemplate.setRepeated(redPacketTemplateInfoDto.getRepeated());
                redPacketTemplate.setModel(redPacketTemplateInfoDto.getModel());
                redPacketTemplate.setUpdateTime(now);
                redPacketTemplateMapper.updateById(redPacketTemplate);
            }
        }else{

            //根据名称查询
            RedPacketTemplate redPacketTemplate_name = redPacketTemplateMapper.selectByName(redPacketTemplateInfoDto.getMerId(), redPacketTemplateInfoDto.getName());
            if (redPacketTemplate_name != null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "模板名称不能重复");
            }

            RedPacketTemplate redPacketTemplate = new RedPacketTemplate();
            redPacketTemplate.setId(IdWorker.getId());
            redPacketTemplate.setMerId(redPacketTemplateInfoDto.getMerId());
            redPacketTemplate.setTitle(redPacketTemplateInfoDto.getTitle());
            redPacketTemplate.setDesc(redPacketTemplateInfoDto.getDesc());
            redPacketTemplate.setImg(redPacketTemplateInfoDto.getImg());
            redPacketTemplate.setReplay(redPacketTemplateInfoDto.getReplay());
            redPacketTemplate.setName(redPacketTemplateInfoDto.getName());
            redPacketTemplate.setMoney(redPacketTemplateInfoDto.getMoney());
            redPacketTemplate.setRepeated(redPacketTemplateInfoDto.getRepeated());
            redPacketTemplate.setModel(redPacketTemplateInfoDto.getModel());
            redPacketTemplate.setUpdateTime(now);
            redPacketTemplate.setCreateTime(now);
            redPacketTemplateMapper.insert(redPacketTemplate);
        }
    }

    /**
     * 删除红包模板
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param redPacketTemplateIdDto
     * @return null
     */
    public void deleteRedPacketTemplate(RedPacketTemplateIdDto redPacketTemplateIdDto){
        Long id = redPacketTemplateIdDto.getId();
        if(id == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入红包模板id");
        }
        redPacketTemplateMapper.deleteById(redPacketTemplateIdDto.getId(), redPacketTemplateIdDto.getMerId());
    }

}
